<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <!--[if lt IE 9]>
    <script type="text/javascript" src="http://libs.useso.com/js/html5shiv/3.7/html5shiv.min.js"></script>
    <script type="text/javascript" src="http://libs.useso.com/js/respond.js/1.4.2/respond.min.js"></script>
    <script type="text/javascript" src="http://cdn.bootcss.com/css3pie/2.0beta1/PIE_IE678.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="../../h-ui/css/H-ui.min.css"/>
    <link rel="stylesheet" type="text/css" href="../../h-ui.admin/css/H-ui.admin.css"/>
    <link rel="stylesheet" type="text/css" href="../../lib/Hui-iconfont/1.0.8/iconfont.css"/>
    <link rel="stylesheet" type="text/css" href="../../h-ui.admin/skin/default/skin.css" id="skin"/>
    <link rel="stylesheet" type="text/css" href="../../h-ui.admin/css/style.css"/>
    <link rel="stylesheet" href="../../lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="../../lib/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="../../lib/layer/2.4/layer.js"></script>
    <script type="text/javascript" src="../../h-ui/js/H-ui.min.js"></script>
    <script type="text/javascript" src="../../h-ui.admin/js/H-ui.admin.js"></script>
    <!--[if IE 7]>
    <link href="http://www.bootcss.com/p/font-awesome/assets/css/font-awesome-ie7.min.css" rel="stylesheet"
          type="text/css"/>
    <![endif]-->
    <title>添加用户</title>
</head>
<body>
<div class="pd-20">
    <div class="Huiform">
        <input type="hidden" name="ckdTree" id="ckdTree">
        <input type="hidden" name="ckdTreePer" id="ckdTreePer">
        <form action="" method="post" id="formData">
            <input type="hidden" name="roleid" id="roleid">
            <table class="table table-bg">
                <tbody>
                <tr>
                    <th width="100" class="text-r"><span class="c-red">*</span>角色名称：</th>
                    <td><input type="text" style="width:200px" class="input-text" value="" placeholder=""
                               id="rolename" name="rolename" datatype="*2-16" nullmsg="角色名称不能为空"></td>
                </tr>
                <tr>
                    <th width="100" class="text-r"><span class="c-red">*</span> 排序号：</th>
                    <td><input type="text" style="width:200px" class="input-text" value="" placeholder="" id="roledesc"
                               name="roledesc" datatype="*2-16" nullmsg="排序号不能为空"></td>
                </tr>
                <tr>
                    <th width="100" class="text-r"><span class="c-red"></span></th>
                    <td>
                        <table class="table table-bg">
                            <tr>
                                <td>人员选择</td>
                                <td> 权限选择</td>
                            </tr>
                            <tr>
                                <td style="vertical-align:top">
                                    <div id="userTree" class="ztree">
                                    </div>
                                </td>
                                <td style="vertical-align:top">
                                    <div id="permissionTree" class="ztree">
                                    </div>
                                </td>
                            </tr>
                        </table>

                    </td>

                </tr>
                </tbody>
            </table>
        </form>
        <button class="btn btn-success radius" type="" id="save"><i class="icon-ok"></i> 确定</button>
    </div>
</div>
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="../../js/Validform_v5.3.2_min.js"></script>
<script type="text/javascript" src="../../js/H-ui.js"></script>
<script type="text/javascript" src="../../js/H-ui.admin.js"></script>
<script type="text/javascript" src="../../lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript">
    $(".Huiform").Validform();
</script>
<script>
    var setting = {
        check: {
            enable: true
        },
        view: {
            dblClickExpand: false,
            showLine: false,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        }
    };
    var zNodesUser;
    var zNodesPer;

    window.onload = (function () {
        //异步获取人员树
        $.ajax({
            type: 'POST',
            url: '/common/selectUserList',
            dataType: 'json',
            success: function (data) {
                zNodesUser = data.data;
                var t = $("#userTree");
                t = $.fn.zTree.init(t, setting, zNodesUser);
            }
        })

        //异步获取权限
        $.ajax({
            type: 'POST',
            url: '/common/selectPermissionList',
            dataType: 'json',
            success: function (data) {
                zNodesPer = data.data;
                var p = $("#permissionTree");
                p = $.fn.zTree.init(p, setting, zNodesPer);
            }
        })

        //编辑页面，不是新增的
        if (getQueryVariable("roleid") != "false") {
            var roleid = getQueryVariable("roleid");
            var jsonArray = [];
            if (roleid != null && roleid != "") {
                var obj = {'column': "roleid", 'type': 'eq', "value": roleid};
                jsonArray.push(obj)
            }
            $.ajax({
                type: 'POST',
                url: '/role/find',
                dataType: 'json',
                data: {paramData: JSON.stringify(jsonArray)},
                success: function (data) {
                    //alert(data.data.toString());
                    cpJsonToForm(data.data, "formData");
                    //根据角色id获取该角色对应的人员
                    var uRQuery = {'column': "rid", 'type': 'eq', "value": data.data.roleid};
                    var uRQueryJsonArray = [];
                    uRQueryJsonArray.push(uRQuery);
                    //获取对应角色的人员
                    $.ajax({
                        type: 'POST',
                        url: '/user-role/all',
                        dataType: 'json',
                        data: {paramData: JSON.stringify(uRQueryJsonArray)},
                        success: function (data) {
                            zTreeOnAsyncSuccess();
                            //    alert(data.data.toString());
                            var treeObj = $.fn.zTree.getZTreeObj("userTree")
                            for (var i = 0; i < data.data.length; i++) {
                                var node = treeObj.getNodeByParam("id", data.data[i].uid);//根据ID找到该节点
                                if (node != null) {
                                    treeObj.checkNode(node, true, false);//根据该节点选中
                                }
                            }
                        }
                    })
                    //获取对应角色的权限
                    $.ajax({
                        type: 'POST',
                        url: '/role-permission/all',
                        dataType: 'json',
                        data: {paramData: JSON.stringify(uRQueryJsonArray)},
                        success: function (data) {
                            var treeObj = $.fn.zTree.getZTreeObj("permissionTree")
                            for (var i = 0; i < data.data.length; i++) {
                                var node = treeObj.getNodeByParam("id", data.data[i].pid);//根据ID找到该节点
                                if (node != null) {
                                    treeObj.checkNode(node, true, false);//根据该节点选中
                                }
                            }
                        }
                    })
                }
            })
        }

    });

    $("#save").click(function () {
        var roleid = $("#roleid").val();
        if (roleid != null && roleid != "") {
            save(1);
        } else {
            save(0);
        }

    })

    function save(type) {
        var url;
        if (type == 0) {
            url = '/role/add';
        } else {
            url = '/role/update';
        }
        var formObject = {};
        var formArray = $("#formData").serializeArray();
        $.each(formArray, function (i, item) {
            formObject[item.name] = item.value;
        });
        //  alert(JSON.stringify(formObject));
        $.ajax({
            url: url,
            type: "post",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formObject),
            dataType: "json",
            success: function (data) {
                var rId = data.msg;
                //获取选中的节点
                onCheck();
                $.ajax({
                    url: "/common/editUserRole",
                    type: "post",
                    data: "rId=" + rId + "&userIds=" + $("#ckdTree").val(),
                    dataType: "json",
                    success: function (data) {
                        //获取选中的节点
                        onCheckPer();
                        $.ajax({
                            url: "/common/editURolePermission",
                            type: "post",
                            data: "rId=" + rId + "&pIds=" + $("#ckdTreePer").val(),
                            dataType: "json",
                            success: function (data) {
                                alert(data.msg);
                                window.opener.loadlist();
                                window.close();
                            }
                        });
                    }

                });

            },
            error: function () {
                console.log("提交ajax函数异常");
            },

        });
    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return "flase";
    }

    var cpJsonToForm = function (json, formId) {
        var serializeArray = $("#" + formId).serializeArray();
        for (var i = 0; i < serializeArray.length; i++) {
            var name = serializeArray[i].name;
            if (json[name]) {
                var value = json[name];
                $("[name='" + name + "']").val(value);
            }
        }
    };

    function comboTree() {
        $.ajax({
            url: "/common/selectDept",
            type: "POST",
            dataType: "json",
            success: function (data) {
                $('#showId').combotree(
                    'loadData',
                    eval(data.msg));
                var checkV = ($("#parId").val());
                if (checkV != null && checkV != "") {
                    $('#showId').combotree('setValue', checkV);
                }

            },
            error: function () {
                alert("error")
            }
        });
    }

    /**
     * 在zTree选择的时候，记住选择的子节点ID，逗号分隔
     * @param e
     * @param treeId
     * @param treeNode
     */
    function onCheck(e, treeId, treeNode) {
        var treeObj = $.fn.zTree.getZTreeObj("userTree"),
            nodes = treeObj.getCheckedNodes(true),
            v = "";
        for (var i = 0; i < nodes.length; i++) {
            if (!nodes[i].isParent) {
                v += nodes[i].id + ",";
            }
        }
        $("#ckdTree").val(v);
    }

    /**
     * 在zTree选择的时候，记住选择的子节点ID，逗号分隔
     * @param e
     * @param treeId
     * @param treeNode
     */
    function onCheckPer(e, treeId, treeNode) {
        var treeObj = $.fn.zTree.getZTreeObj("permissionTree"),
            nodes = treeObj.getCheckedNodes(true),
            v = "";
        for (var i = 0; i < nodes.length; i++) {
            if (!nodes[i].isParent) {
                v += nodes[i].id + ",";
            }
        }
        $("#ckdTreePer").val(v);
    }

    /**
     * 用于捕获异步加载正常结束的事件回调函数
     * @param event
     * @param treeId
     * @param treeNode
     * @param msg
     */
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var treeObj = $.fn.zTree.getZTreeObj("userTree");
        var nodes = treeObj.getNodes();
        if (nodes.length > 0) {
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].isParent) {
                    treeObj.expandNode(nodes[i], true, false, false);//默认展开第一级节点
                }
            }
        }
    }
</script>
</body>
</html>
